﻿using MongoRepository;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Tradukisto.Engine.Utilities;
using Tradukisto.Model;

namespace Tradukisto.Engine.ResourceProviders
{
    public class LocalizationMongoDBProvider : LocalizationProviderBase
    {
        private MongoRepository<LocalItem> repo = null;

        public LocalizationMongoDBProvider()
        {
            var connectionString = ConfigurationManager.ConnectionStrings[LocalizationConstants.MONGODB_CONNECTIONSTRING].ToString();
            repo = new MongoRepository<LocalItem>(connectionString);
        }
        protected override string OnGetString(string cultureName, string key)
        {
            var ret = repo.All().Where(p => p.Culture.Equals(cultureName) && p.Name.Equals(key)).SingleOrDefault();

            if (ret == null)
            {
                SimpleLogger.WriteWarning(string.Format("Missing localization to {0} in {1}.", key, cultureName));
                return "";
            }
            return ret.Value;
        }

        public override Dictionary<string, string> GetAllStringsByControllerAndAction(string culture, string controller, string action)
        {
            var pageItems = repo.All().Where(p => p.ActionName.Equals(action) && p.ControllerName.Equals(controller) && p.Culture.Equals(culture)).
                ToDictionary(p => p.Name, x => x.Value);

            return pageItems;
        }

        public override Dictionary<string, string> GetAllStringsByControllerAndAction(string controller, string action)
        {
            return GetAllStringsByControllerAndAction(LocalizationProvider.CultureName, controller, action);
        }
    }
}
